<script>
import audioIcon from "./assets/audio.png";
import stopIcon from "./assets/stop.png";
import { getShowImage, randomString, showToast } from "../utils";
import persistence from "../store/persistence";

let innerAudioContext;
export default {
  name: "audio",
  data() {
    return {
      audioIcon,
      stopIcon,
      playing: false,
      autoPlay: true,
    };
  },
  props: {
    audioSrc: {
      type: String,
      default: "",
    },
    text: {
      type: String,
      default: "",
    },
    allowAutoPlay: {
      type: Boolean,
      default: true,
    },
  },
  beforeDestroy() {
		innerAudioContext && innerAudioContext.destroy();
  },
  watch: {
    audioSrc: {
      handler(src) {
        if (src) {
          this.autoPlay = persistence.getters.getAutoAudioSetting();
          innerAudioContext = uni.createInnerAudioContext();
          if (this.autoPlay && this.allowAutoPlay) {
            this.play();
          }
        }
      },
      immediate: true,
    },
  },
  methods: {
    init() {
      let that = this;
      //取消绑定先前绑定的事件
      innerAudioContext.offPlay();
      innerAudioContext.onPlay(() => {
        that.playing = true;
      });
      innerAudioContext.onStop(() => {
        that.playing = false;
      });
      innerAudioContext.onEnded(() => {
        that.playing = false;
      });
      innerAudioContext.onError((error) => {
        // showToast.error("播放失败");
        console.log(error, "error");
        that.playing = false;
      });
    },
    play() {
      this.init();
      innerAudioContext.src = getShowImage(this.audioSrc);
      innerAudioContext.play();
    },
    stop() {
      innerAudioContext.stop();
    },
  },
};
</script>

<template>
  <view class="component">
    <view class="text">{{ text }}</view>
    <template v-if="audioSrc">
      <image
        class="icon"
        :src="audioIcon"
        v-if="!playing"
        @click="play"
      ></image>
      <image class="icon" :src="stopIcon" v-else @click="stop"></image>
    </template>
  </view>
</template>

<style scoped lang="scss">
.component {
  display: flex;
  align-items: center;

  .text {
    font-size: 32rpx;
    color: var(--text-color-light);
  }

  .icon {
    width: 60rpx;
    height: 60rpx;
  }
}
</style>
